<?php namespace Admin\Controller;
use Hdphp\Controller\Controller;
class GoodsController extends Controller{
	
	private $GoodsModel;
	private $CategoryModel;
	private $BrandModel;
	private $TypeAttrModel;
	private $GoodsDetailModel;
	private $GoodsAttrModel;

	public function __init(){	
		$this->GoodsModel=M('\Common\Model\sc_goods');
		$this->CategoryModel=M('\Common\Model\sc_category');
		$this->BrandModel=M('\Common\Model\sc_brand');
		$this->TypeAttrModel=M('\Common\Model\sc_typeAttr');
		$this->GoodsDetailModel=M('\Common\Model\sc_detail');
		$this->GoodsAttrModel=M('\Common\Model\sc_goods_attr');
		if(!isset($_SESSION['info'])){
			go('Login/index');
		}
	}
	
	
	//首页
	public function index(){
		
		$goodsData=$this->GoodsModel->getGoods();
		if(!$goodsData){
			View::error('没有商品信息，请添加商品！',U('addGoods'));
		}
		
		View::with('goodsData',$goodsData);
		View::make();
	}
	
	
	//添加商品
	public function addGoods(){
		if(IS_POST){
			if($this->GoodsModel->addGoods()) View::success('添加成功！',U('index'));
            View::error($this->GoodsModel->getError());
		}
		//获取分类数据
		$CateData=$this->CategoryModel->getCategory();
		$CateData=Data::tree($CateData,'cname','cid','pid');
		View::with('CateData',$CateData);

		//获取品牌
		$BrandData=$this->BrandModel->getBrand();
		View::with('BrandData',$BrandData);
		
		View::make();
	}
	
	
	public function editGoods(){
			
		if(IS_POST){

			//添加商品数据
			if($this->GoodsModel->saveOneGoods()) View::success('修改成功！',U('index'));
			View::error($this->GoodsModel->getError());

			
           
		}	
		//获取旧数据·············
		$oldData=$this->GoodsModel->getOneGoods();
		View::with('oldData',$oldData);
		
		//获取分类信息
		$CateData=$this->CategoryModel->getCategory();
		$CateData=Data::tree($CateData,'cname','cid','pid');
		View::with('CateData',$CateData);
	    
		//获取品牌信息
		$BrandData=$this->BrandModel->getBrand();
		View::with('BrandData',$BrandData);
	    
		//获取商品详细信息
		$GoodsDetailData=$this->GoodsDetailModel->getOneDetail();
		$GoodsDetailData['big']=explode("|", $GoodsDetailData['big']);
		View::with('GoodsDetailData',$GoodsDetailData);
	
	    //获取商品属性和规格
	    $GoodsAttrData=$this->GoodsAttrModel->getOneGoodsAttr();
		View::with('GoodsAttrData',$GoodsAttrData);
	
	  
	    
		View::make();	
	}
	
	
	
	public function upload(){
		$files = Upload::path('Upload/Content/' . date('y/m'))->make();
	    if (empty($files)) {
	        // 相当于：echo json_encode(Upload::getError());exit;
	        $this->ajax(Upload::getError());
	    } else {
	        //上传成功，把上传好的信息返给js 也就是uploadify
	        $data = $files[0];
	        // 相当于：echo json_encode($data);exit;
	        $this->ajax($data);
	    }	
	}

     //添加商品的时候，获取商品属性
     public function getAttr(){
     	//得到类型id
     	$tid=Q('post.t',0,'intval');
		//通过类型id找到类型属性
		$data=$this->TypeAttrModel->where('sc_type_tid',$tid)->get();
		
		foreach($data as $k=>$v){
			$data[$k]['tavalue']=explode('|',$v['tavalue']);
		}
		
		echo json_encode($data);exit;
     }
	
	
}
